package cz.data.domain.metadata.listener;

import com.alibaba.fastjson.JSONObject;
import cz.data.common.database.CacheDataSourceBean;
import cz.data.common.rabbitmq.config.RabbitConstant;
import cz.data.domain.metadata.explore.RemoteDriverMetadataExplore;
import cz.data.domain.metadata.listener.event.MetadataExploreEvent;
import cz.data.domain.metadata.listener.event.MetadataSourceChangeEvent;
import cz.data.domain.metadata.listener.event.MetadataSourceDeleteEvent;
import cz.data.domain.metadata.listener.event.MetadataTableDeleteEvent;
import cz.data.domain.metadata.service.MetadataColumnService;
import cz.data.domain.metadata.service.MetadataTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class SpringEventListener {

    @Resource
    MetadataTableService tableService;
    @Resource
    MetadataColumnService columnService;
    @Resource
    RemoteDriverMetadataExplore remoteDriverMetadataExplore;
    @Resource
    RabbitTemplate rabbitTemplate;

    @EventListener(MetadataSourceChangeEvent.class)
    public void metadataSourceChange(MetadataSourceChangeEvent event) {
        String sourceId = event.getSourceId();
        JSONObject payload = new JSONObject(1);
        payload.put("data", sourceId);
        log.info("监听到数据源{}变更事件,发送广播通知", sourceId);
        rabbitTemplate.convertAndSend(RabbitConstant.DSC_FANOUT_EXCHANGE, "", payload);
        CacheDataSourceBean.invalid(sourceId);
    }

    @EventListener(MetadataSourceDeleteEvent.class)
    public void metadataSourceDelete(MetadataSourceDeleteEvent event) {
        log.info("监听到数据源{}删除事件 删除数据源下元数据表", event.getMetadataSourceId());
        tableService.deleteMetadataTableBySourceId(event.getMetadataSourceId());
    }

    @EventListener(MetadataTableDeleteEvent.class)
    public void metadataTableDelete(MetadataTableDeleteEvent event) {
        log.info("监听到元数据表{}删除事件 删除元数据表下元数据列", event.getMetadataTableId());
        columnService.deleteMetadataColumnByTableId(event.getMetadataTableId());
    }

    @EventListener(MetadataExploreEvent.class)
    public void metadataExplore(MetadataExploreEvent event) {
        remoteDriverMetadataExplore.explore(event.getMetadataSource());
    }
}
